<template>
    <div class="common-layout">
        <el-container>
            <el-header style="height: 100px;">
                <!-- 面包屑 -->
                <el-breadcrumb :separator-icon="ArrowRight" style="margin-bottom: 20px;">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item :to="{ path: '/' }">流程引擎</el-breadcrumb-item>
                    <el-breadcrumb-item>表单管理</el-breadcrumb-item>
                </el-breadcrumb>

                <!-- 查询条件 -->
                <el-card>
                    <el-row>
                        <el-col :span="5">
                            <el-text>表单名称:</el-text>
                            <el-input placeholder="请输入表单名称" v-model="searchForm.formName"
                                style="width: 70%;margin-left: 10px;" />
                        </el-col>
                        <el-col :span="5">
                            <el-text> 表单分类:</el-text>
                            <el-select v-model="searchForm.typeId" placeholder="请选择表单分类" style="width: 70%;" clearable>
                                <el-option v-for="item in formTypeDropData" :key="item.TypeId" :label="item.TypeName"
                                    :value="item.TypeId" />
                            </el-select>
                        </el-col>
                        <el-col :span="5">
                            <el-text> 行业名称：</el-text>
                            <el-select v-model="searchForm.professionalId" placeholder="请选择行业名称" style="width: 70%;"
                                clearable>
                                <el-option label="行政" value="1" />
                                <el-option label="公安" value="2" />
                            </el-select>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="primary" @click="handleSearch">搜索</el-button>
                            <el-button @click="handleReset">重置</el-button>
                        </el-col>
                    </el-row>
                </el-card>

            </el-header>
            <!-- 表单数据列表 -->
            <el-main>
                <el-card>
                    <el-row>
                        <el-col>
                            <el-button type="primary" @click="dialogFormVisible = true"> 添加</el-button>
                        </el-col>
                    </el-row>
                    <el-table :data="tableData" stripe style="width: 100%">
                        <el-table-column prop="FormId" label="表单Id" />
                        <el-table-column prop="FormNo" label="表单编号" />
                        <el-table-column prop="FormName" label="表单名称" />
                        <el-table-column prop="TypeNo" label="分类编号" />
                        <el-table-column prop="TypeName" label="分类名称" />
                        <el-table-column label="所属行业">
                            <template #default="scope">
                                <el-tag v-if="scope.row.ProfessionalId == 1">刑事</el-tag>
                                <el-tag v-else-if="scope.row.ProfessionalId == 2">民事</el-tag>
                                <el-tag v-else>行政</el-tag>
                            </template>
                        </el-table-column>

                        <el-table-column>
                            <template #default="scope">
                                <el-button type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                                <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
                                <el-button type="primary" @click="handleFormDetailSetting(scope.row)">添加表单明细</el-button>
                                <el-button type="primary"
                                    @click="handleFormNodeSetting(scope.row.FormId)">添加表单节点</el-button>
                                <el-button type="primary"
                                    @click="openFormFlowSetting(scope.row.FormId)">设置表单流程</el-button>


                            </template>
                        </el-table-column>

                    </el-table>

                    <Pagination :current-page="searchForm.pageIndex" :page-size="searchForm.pageSize"
                        :total-count="searchForm.totalCount" :total-page="searchForm.totalPage"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </Pagination>

                </el-card>
            </el-main>
        </el-container>
    </div>

    <!-- 添加表单弹出框 -->
    <el-dialog v-model="dialogFormVisible" title="添加表单数据" width="500">
        <el-form :model="inputData">
            <el-form-item label="表单名称" :label-width="formLabelWidth">
                <el-input v-model="inputData.formName" autocomplete="off" />
            </el-form-item>

            <el-form-item label="表单分类" :label-width="formLabelWidth">
                <el-select v-model="inputData.typeId" placeholder="请选择表单分类" style="width: 70%;" clearable>
                    <el-option v-for="item in formTypeDropData" :key="item.TypeId" :label="item.TypeName"
                        :value="item.TypeId" />
                </el-select>
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleSubmit">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 表单明细对话框 -->
    <el-dialog v-model="dialogFormDetailVisible" title="表单明细操作" width="1600">

        <el-row>
            <el-col>
                <el-button type="primary" @click="handleFormDetailRowAdd"> 添加</el-button>
            </el-col>
        </el-row>

        <el-table :data="formDetailData">
            <el-table-column type="index" label="行号" width="180" />
            <el-table-column property="FieldName" label="字段名称">
                <template #default="scope">
                    <el-input v-model="scope.row.FieldName" />
                </template>
            </el-table-column>
            <el-table-column property="FieldDesc" label="字段描述">
                <template #default="scope">
                    <el-input v-model="scope.row.FieldDesc" />
                </template>
            </el-table-column>
            <el-table-column property="FieldType" label="字段类型">
                <template #default="scope">
                    <el-select v-model="scope.row.FieldType" placeholder="请选择字段类型" style="width: 90%;" clearable>
                        <el-option label="字符串" value="string" />
                        <el-option label="整型" value="int" />
                        <el-option label="浮点" value="float" />
                        <el-option label="布尔" value="bool" />
                        <el-option label="日期" value="date" />
                        <el-option label="时间" value="datetime" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column property="FieldControl" label="控件类型">
                <template #default="scope">
                    <el-select v-model="scope.row.FieldControl" placeholder="请选择控件类型" style="width: 90%;" clearable>
                        <el-option label="文本框" value="text" />
                        <el-option label="下拉框" value="select" />
                        <el-option label="单选框" value="radio" />
                        <el-option label="复选框" value="checkbox" />
                        <el-option label="日期选择器" value="date" />
                        <el-option label="时间选择器" value="datetime" />
                        <el-option label="文本域" value="textarea" />
                    </el-select>
                </template>
            </el-table-column>

            <el-table-column property="FieldProperties" label="控件属性" width="350%">
                <template #default="scope">
                    <el-input v-model="scope.row.FieldProperties" style="width: 50%;margin-right: 10px;" disabled />
                    <el-button type="primary" @click="handleFormDetailPropertiesSetting(scope.row)">设置</el-button>
                    <el-button type="danger" @click="handleFormDetailRowDelete(scope.row)">清空</el-button>
                </template>
            </el-table-column>
            <el-table-column property="FieldDefaultValue" label="默认值">
                <template #default="scope">
                    <el-input v-model="scope.row.FieldDefaultValue" />
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="120">
                <template #default="scope">
                    <el-button type="danger" @click="handleFormDetailRowDelete(scope.row)">删除</el-button>
                </template>

            </el-table-column>
        </el-table>

        <template #footer="scope">
            <div class="dialog-footer">
                <el-button @click="dialogFormDetailVisible = false">取消</el-button>
                <el-button type="primary" @click="handleFormDetailSave()">确认</el-button>
            </div>
        </template>

    </el-dialog>

    <!-- 表单明细空间属性弹出框 -->
    <el-dialog v-model="dialogFormDetailPropertiesVisible" title="控件属性操作" width="700">
        <el-row>
            <el-col>
                <el-button type="primary" @click="handleFormDetailPropertiesRowAdd"> 添加</el-button>
            </el-col>
        </el-row>
        <el-table :data="formDetailPropertieData">

            <el-table-column type="index" label="行号" />
            <el-table-column property="value" label="属性名称">
                <template #default="scope">
                    <el-input v-model="scope.row.label" />
                </template>
            </el-table-column>

            <el-table-column property="value" label="属性值">
                <template #default="scope">
                    <el-input v-model="scope.row.value" />
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="120">
                <template #default="scope">
                    <el-button type="danger" @click="handleFormDetailPropertiesRowDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormDetailPropertiesVisible = false">取消</el-button>
                <el-button type="primary" @click="handleFormDetailPropertiesSave()">确认</el-button>
            </div>
        </template>
    </el-dialog>


    <!-- 表单节点弹出框 -->
    <el-dialog v-model="dialogFormNodesPropertiesVisible" title="表单节点-新增" width="700">
        <el-form :model="formNodePropertieData">
            <el-form-item label="节点名称" :label-width="formLabelWidth">
                <el-input v-model="formNodePropertieData.NodeName" autocomplete="off" />
            </el-form-item>
        </el-form>

        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="addFromNode">
            提交
        </el-button>
    </el-dialog>>

    <!-- 表单节点列表弹出框 -->
    <el-dialog v-model="dialogFormNodesShowPropertiesVisible" title="表单流转设置" width="1500">
        <!-- 节点查询 -->
        节点名称：
        <el-input placeholder="请输入节点名称" style="width: 200px;" v-model="formNodesqueryInfo.NodeName"></el-input>
        &nbsp;
        所属表单：
        <el-select placeholder="请选择表单" v-model="formNodesqueryInfo.FormId" style="width: 150px;">
            <el-option v-for="item in formData" :value="item.FormId" :label=item.FormName>{{ item.FormName
            }}</el-option>
        </el-select>
        所属表单分类：
        <el-select placeholder="请选择表单分类" v-model="formNodesqueryInfo.FormTypeId" style="width: 150px;">
            <el-option v-for="item in formTypeDropData" :value="item.TypeId" :label=item.TypeName>{{ item.TypeName
            }}</el-option>
        </el-select>
        <br>

        <el-button @click="formNodesShowList" type="primary" style="margin: 20px;">查询</el-button>
        &nbsp;
        <el-button @click="Resert" type="danger">重置</el-button>

        <!-- 节点列表 -->
        <el-table :data="FormNodeInfoList.pageData" style="width: 100%; margin: 30px;" ref="formNodesTableRef">
            <el-table-column fixed type="index" label="序号" width="150" />
            <el-table-column prop="NodeNo" label="节点编号" width="150" />
            <el-table-column prop="NodeName" label="节点名称" />
            <el-table-column label="操作人" width="200">
                <template #default="scope">
                    <el-select v-model="scope.row.OperatorUserId" placeholder="请选择操作人" style="width: 100%;" clearable>
                        <el-option v-for="user in userList" :key="user.AccountId" :label="user.NickName"
                            :value="user.AccountId" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="PrevNodeName" label="上级节点名称" width="150" />
            <el-table-column prop="NextNodeName" label="下级节点名称" width="150" />
            <el-table-column prop="FormName" label="表单名称" width="150" />
            <el-table-column prop="TypeName" label="分类名称" width="150" />

            <el-table-column fixed="right" label="操作列" min-width="120">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="formNodesDel(scope.row.NodeId)">
                        删除
                    </el-button>
                    <el-button link type="primary" size="small" @click="">修改</el-button>
                </template>
            </el-table-column>

        </el-table>

        <!-- <Pagination :current-page="formNodesqueryInfo.PageIndex" :page-size="formNodesqueryInfo.PageSize"
            :total-count="FormNodeInfoList.TotalCount" :total-page="FormNodeInfoList.TotalPage"
            @size-change="handleSizeChange" @current-change="handleCurrentChange">
        </Pagination> -->

        <!-- 添加对话框的footer插槽，包含保存和取消按钮 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormNodesShowPropertiesVisible = false">取消</el-button>
                <el-button type="primary" @click="handleFormNodeSave()">确认</el-button>
            </div>
        </template>
    </el-dialog>>

    <!-- 在合适位置添加FormFlowSetting组件 -->
    <FormFlowSetting ref="formFlowSettingRef" />

</template>


<script lang="ts" setup>
import { ArrowRight, CirclePlus, Search } from '@element-plus/icons-vue'
import { onMounted, reactive, ref, watch, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination.vue'
import { addFormInfo, getFormInfo, deleteFormInfo, updateFormInfo, getFormList } from '@/api/formInfo'//引入表单管理的接口
import { GetFormTypeList } from '@/api/formType'//引入表单类型管理的接口
import { fetchFormDetailSave, getfetchFormDetail } from '@/api/formDetail'//引入表单明细管理的接口
import { AddFromNode, GetFromNode, DeleteFromNode, UpdateFromNode, SaveFormNodeDetails } from '@/api/formNode'//引入表单接地那管理的接口
import { GetAccount } from '@/api/user'; // 新增：引入获取用户账户的API
import Sortable from 'sortablejs'; // 引入SortableJS
import FormFlowSetting from '@/views/FormNode/FormFlowSetting.vue'
import type { ComponentPublicInstance } from 'vue'


//定义表单类型下拉框数据的接口
interface FormTypeDropData {
    TypeId: string
    TypeName: number
}

//定义表单数据的接口
interface FormDropData {
    FormId: number
    FormName: string
}


//定义表单明细数据的接口
interface FormDetailData {
    FormDetailId: number
    FormId: number
    FieldName: string
    FieldDesc: string
    FieldType: string
    FieldControl: string
    FieldProperties: string
    FieldDefaultValue: string
}

//定义表单明细控件属性数据的接口
interface FormDetailPropertiesData {
    value: string
    label: string
}



//定义查询条件
const searchForm = reactive({
    formName: '',
    typeId: null,
    professionalId: null,
    pageIndex: 1,
    pageSize: 3,
    totalCount: 0,
    totalPage: 0
})

//定义行业数据
const professionalData = ref([
    { label: '行政', value: 1 },
    { label: '公安', value: 2 },
    { label: '消防', value: 3 },
    { label: '交通', value: 4 }
])

//初始化表单数据
const initInputForm = reactive({
    formId: null,
    formName: '',
    typeId: ''
})

//初始化表单节点数据
const FormNodePropertiesData = reactive({
    NodeName: '',
    FormId: 0
})

//定义表格数据
const tableData = ref();

//定义表单数据的数组
const formData = ref<FormDropData[]>([]);
//定义弹出框
const dialogFormVisible = ref(false)
//定义表单明细弹出框
const dialogFormDetailVisible = ref(false)
//定义表单明细控件属性弹出框
const dialogFormDetailPropertiesVisible = ref(false)
//定义表单节点控件属性弹出框
const dialogFormNodesPropertiesVisible = ref(false)
//定义表单节点列表的弹出框
const dialogFormNodesShowPropertiesVisible = ref(false)
//定义空间宽度
const formLabelWidth = ref('120px')
//定义表单分类下拉框数据
const formTypeDropData = ref<FormTypeDropData[]>([])
//定义表单数据
const inputData = reactive({ ...initInputForm })
//定义表单节点数据
const formNodePropertieData = reactive({ ...FormNodePropertiesData })

//定义表单明细数据
const formDetailData = ref<FormDetailData[]>([])
//定义表单明细控件属性数据
const formDetailPropertieData = ref<FormDetailPropertiesData[]>([])

//定义当前正在操作的明细 ID
const currentFormDetailId = ref(0)

// Ref for the sortable table and Sortable instance
const formNodesTableRef = ref(null);
const sortableInstance = ref<Sortable | null>(null);

const formFlowSettingRef = ref<ComponentPublicInstance<{ open: (formId: number) => void }> | null>(null)

//#region 表单相关操作  

//获取表单数据
const getFormData = async () => {
    const res = await getFormList(0)
    console.log(res);
    formData.value = res.data.Result
}

// 获取行业标签
const getIndustryLabel = (id: number) => {
    const industry = professionalData.value.find(item => item.value === id)
    return industry ? industry.label : '未知行业'
}

//分页
const handleSizeChange = (val: number) => {
    searchForm.pageSize = val;
    handleSearch()
}
const handleCurrentChange = (val: number) => {
    searchForm.pageIndex = val;
    handleSearch()
}

//重置查询条件
const handleReset = () => {
    searchForm.formName = ''
    searchForm.typeId = null
    searchForm.professionalId = null
}

//编辑表单信息
const handleEdit = async (row: any) => {

    console.log(row)

    // 填充表单数据
    Object.assign(inputData, row)

    // 打开编辑弹出框
    dialogFormVisible.value = true
}

//弹出框的取消
const handleCancel = () => {
    // 关闭弹出框
    dialogFormVisible.value = false
    //重置表单数据
    Object.assign(inputData, initInputForm)
}

//表单分类下拉框
const getformTyprList = async () => {

    const res = await GetFormTypeList();

    console.log(res);

    formTypeDropData.value = res.data.Result
}

//提交事件
const handleSubmit = async () => {
    if (inputData.formId) {
        // 如果存在 typeId，说明是编辑
        await updateFormInfo(inputData)
        ElMessage.success("修改表单分类成功")
    } else {
        // 否则是新增
        await addFormInfo(inputData)
        ElMessage.success("新增表单分类成功")
    }

    // 重新加载表格数据
    await handleSearch()
    // 重置表单数据
    Object.assign(inputData, initInputForm)
    // 关闭弹出框
    dialogFormVisible.value = false
}


//查询表单 表单数据列表
const handleSearch = async () => {

    // 发送请求获取数据
    const res = await getFormInfo(searchForm)
    console.log(res);
    tableData.value = res.data.Result.Data
    searchForm.totalCount = res.data.Result.TotalCount
    searchForm.totalPage = res.data.Result.TotalPage
}

//删除表单信息
const handleDelete = async (row: any) => {
    // 确认删除
    ElMessageBox.confirm('确定删除该表单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 删除数据
        await deleteFormInfo(row.formId)
        ElMessage.success("删除表单成功")
        // 重新加载表格数据
        handleSearch()
    })
}

onMounted(async () => {
    getformTyprList();
    handleSearch();
    await getUsers();
})


//#endregion

//#region 表单明细相关操作
//const formidd = ref<number>();

const handleFormDetailSetting = async (row: any) => {



    //拿到当前行的formid
    let formid = row.FormId
    console.log(formid);

    //去后台查询，如果没有数据的话 生成 3 个默认的空数据 
    const formDetaillist = await getfetchFormDetail(formid)
    //如果有数据 就加载后台的数据
    if (formDetaillist.data.Result.length > 0) {
        console.log(formDetaillist.data.Result);
        //把后台数据赋值给数组
        formDetailData.value = formDetaillist.data.Result
    }
    else {//没有数据则生成空数据
        //生成三个默认的空数据
        formDetailData.value = [
            { FormDetailId: 1, FormId: row.FormId, FieldName: '', FieldDesc: '', FieldType: '', FieldControl: '', FieldProperties: '', FieldDefaultValue: '' },
            { FormDetailId: 2, FormId: row.FormId, FieldName: '', FieldDesc: '', FieldType: '', FieldControl: '', FieldProperties: '', FieldDefaultValue: '' },
            { FormDetailId: 3, FormId: row.FormId, FieldName: '', FieldDesc: '', FieldType: '', FieldControl: '', FieldProperties: '', FieldDefaultValue: '' }
        ]
        //打印当前数据
        console.log(formDetailData);
    }



    //显示表单明细对话框
    dialogFormDetailVisible.value = true
}

//表单明细添加一个空行
const handleFormDetailRowAdd = () => {

    //添加一行数据
    formDetailData.value.push({ FormDetailId: generateFakeId(), FormId: 0, FieldName: '', FieldDesc: '', FieldType: '', FieldControl: '', FieldProperties: '', FieldDefaultValue: '' })
}

//表单删除一个空行
const handleFormDetailRowDelete = (row: any) => {
    //删除一行数据
    const index = formDetailData.value.indexOf(row)
    if (index > -1) {
        formDetailData.value.splice(index, 1)
    }
}

//保存表单明细数据
const handleFormDetailSave = async () => {
    console.log(formDetailData.value)

    //formDetailData.value.formId=id

    //去除空数据
    formDetailData.value = formDetailData.value.filter(item => item.FieldName !== '' && item.FieldDesc !== '' && item.FieldType !== '' && item.FieldControl !== '')

    //保存数据到后台
    console.log(formDetailData.value)

    var params = {
        FormDetails: formDetailData.value
    }


    await fetchFormDetailSave(params)
    ElMessage.success("保存表单明细成功")

    //关闭弹出框
    dialogFormDetailVisible.value = false
}



//#endregion

//#region 表单明细控件属性相关操作

//表单明细控件属性添加一个空行
const handleFormDetailPropertiesRowAdd = () => {
    //添加一行数据
    formDetailPropertieData.value.push({ value: '', label: '' })
}
//表单明细控件属性删除一个空行
const handleFormDetailPropertiesRowDelete = (row: any) => {
    //删除一行数据
    const index = formDetailPropertieData.value.indexOf(row)
    if (index > -1) {
        formDetailPropertieData.value.splice(index, 1)
    }
}

const handleFormDetailPropertiesSetting = (row: FormDetailData) => {
    //设置当前正在操作的明细 ID
    currentFormDetailId.value = row.FormDetailId

    try {
        if (row.FieldProperties) {
            const parsed = JSON.parse(row.FieldProperties)
            // 确保解析后是数组
            if (Array.isArray(parsed)) {
                formDetailPropertieData.value = parsed
            } else {
                // 不是数组，重置为默认
                formDetailPropertieData.value = [
                    { value: '', label: '' },
                    { value: '', label: '' },
                    { value: '', label: '' }
                ]
            }
        } else {
            // 没有数据，重置为默认
            formDetailPropertieData.value = [
                { value: '', label: '' },
                { value: '', label: '' },
                { value: '', label: '' }
            ]
        }
    } catch (e) {
        // JSON解析失败，重置为默认
        formDetailPropertieData.value = [
            { value: '', label: '' },
            { value: '', label: '' },
            { value: '', label: '' }
        ]
    }

    //打开表单明细控件属性弹出框
    dialogFormDetailPropertiesVisible.value = true
}

//保存表单明细控件属性数据
const handleFormDetailPropertiesSave = () => {

    //除去formDetailPropertieData里的空数据
    formDetailPropertieData.value = formDetailPropertieData.value.filter(item => item.label !== '' && item.value !== '')

    //保存数据到明细里
    const formDetail = formDetailData.value.find(item => item.FormDetailId === currentFormDetailId.value)
    if (formDetail && formDetailPropertieData.value.length > 0) {
        formDetail.FieldProperties = JSON.stringify(formDetailPropertieData.value)
    }

    //关闭弹出框
    dialogFormDetailPropertiesVisible.value = false
}

//#endregion

//添加表单节点
const handleFormNodeSetting = (id: number) => {
    dialogFormNodesPropertiesVisible.value = true;
    formNodePropertieData.FormId = id;
}

const addFromNode = async () => {

    await AddFromNode(formNodePropertieData);
    ElMessage.success("添加节点成功");
    //添加成功后初始化数据并关闭弹窗
    dialogFormNodesPropertiesVisible.value = false;
    formNodePropertieData.NodeName = '';
    formNodePropertieData.FormId = 0;
}

//生成 fakeID
const generateFakeId = () => {
    return Math.floor(Math.random() * 1000000000)
}

//节点列表
const FormNodeInfoList = reactive({
    TotalCount: 0,
    TotalPage: 0,
    pageData: []
});

const formNodesqueryInfo = reactive({
    FormTypeId: null,
    FormId: null,
    NodeName: '',
    PageIndex: 1,
    PageSize: 10
})


//表单节点数据列表
const formNodesShowList = async () => {
    console.log(formNodesqueryInfo);

    const res = await GetFromNode({
        FormTypeId: formNodesqueryInfo.FormTypeId,
        FormId: formNodesqueryInfo.FormId,
        NodeName: formNodesqueryInfo.NodeName,
        PageIndex: formNodesqueryInfo.PageIndex,
        PageSize: formNodesqueryInfo.PageSize
    })

    //console.log(res);

    FormNodeInfoList.pageData = res.data.Result.Data;
    FormNodeInfoList.TotalCount = res.data.Result.TotalCount;
    FormNodeInfoList.TotalPage = res.data.Result.TotalPage;

}

//查询条件重置按钮
const Resert = () => {
    formNodesqueryInfo.FormId = null;
    formNodesqueryInfo.FormTypeId = null;
    formNodesqueryInfo.NodeName = '';

    formNodesShowList();
}

// 初始化SortableJS
const initSortable = () => {
    if (formNodesTableRef.value) {
        const tableEl = (formNodesTableRef.value as any).$el;
        if (!tableEl) {
            console.error("表格元素不可用");
            return;
        }

        const tbody = tableEl.querySelector('.el-table__body-wrapper tbody');
        if (tbody && !sortableInstance.value) {
            sortableInstance.value = new Sortable(tbody, {
                animation: 150,
                handle: '.el-table__row',
                onEnd: (evt: Sortable.SortableEvent) => {
                    if (evt.oldIndex !== undefined && evt.newIndex !== undefined) {
                        // 获取被拖拽的行
                        const draggedItem = FormNodeInfoList.pageData.splice(evt.oldIndex, 1)[0];
                        // 放到新位置
                        FormNodeInfoList.pageData.splice(evt.newIndex, 0, draggedItem);

                        // 遍历数组，根据位置更新上下级关系
                        FormNodeInfoList.pageData.forEach((node: any, index: number) => {
                            // 根据行的位置设置上级节点
                            if (index === 0) {
                                // 第一行，没有上级
                                node.PrevNodeName = '';
                            } else {
                                // 非第一行，上级是前一行
                                node.PrevNodeName = (FormNodeInfoList.pageData[index - 1] as any).NodeName || '';
                            }

                            // 根据行的位置设置下级节点
                            if (index === FormNodeInfoList.pageData.length - 1) {
                                // 最后一行，没有下级
                                node.NextNodeName = '';
                            } else {
                                // 非最后一行，下级是后一行
                                node.NextNodeName = (FormNodeInfoList.pageData[index + 1] as any).NodeName || '';
                            }
                        });

                        // 强制视图更新
                        nextTick(() => {
                            console.log("数据更新完成，视图刷新");
                        });
                    }
                },
            });
        }
    }
};

// 监听对话框显示状态
watch(dialogFormNodesShowPropertiesVisible, (newValue) => {
    if (newValue) {
        nextTick(() => {
            initSortable();
        });
    } else {
        if (sortableInstance.value) {
            sortableInstance.value.destroy();
            sortableInstance.value = null;
        }
    }
});

// 组件卸载时清理Sortable实例
onUnmounted(() => {
    if (sortableInstance.value) {
        sortableInstance.value.destroy();
        sortableInstance.value = null;
    }
});

//节点删除
const formNodesDel = (id: any) => {
    ElMessageBox.confirm(
        '您确定要删除嘛?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await DeleteFromNode(id);
            ElMessage.success('删除成功')
            formNodesShowList();
            dialogFormNodesShowPropertiesVisible.value = true;
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '操作已取消',
            })
        })
}

//保存表单节点
const handleFormNodeSave = async () => {
    try {
        // 构建要保存的节点数据
        // 这里保存整个节点列表，包括它们的顺序和操作人信息
        const nodesToSave = FormNodeInfoList.pageData.map((node: any) => ({
            NodeId: node.NodeId,
            NodeName: node.NodeName,
            PrevNodeName: node.PrevNodeName,
            NextNodeName: node.NextNodeName,
            FormId: node.FormId,
            OperatorUserId: node.OperatorUserId, // 操作人的AccountId
            // 其他需要保存的节点属性...
        }));

        console.log('准备保存节点数据:', nodesToSave);

        // 调用实际的API保存节点数据
        const response = await SaveFormNodeDetails(nodesToSave);

        if (response && response.data) {
            ElMessage.success("表单节点流程保存成功");
            dialogFormNodesShowPropertiesVisible.value = false;

            // 重新加载节点列表以确认更改
            await formNodesShowList();
        } else {
            ElMessage.warning("保存可能未成功，请检查数据");
        }
    } catch (error) {
        console.error("保存表单节点失败:", error);
        ElMessage.error("保存失败，请重试");
    }
}

//设置表单流程
const openFormFlowSetting = (formId: number) => {
    if (formFlowSettingRef.value && formFlowSettingRef.value.open) {
        formFlowSettingRef.value.open(formId)
    }
}

// 定义用户数据接口 (修改)
interface UserData {
    AccountId: string | number; // 主键ID
    NickName?: string;         // 昵称 (用于显示)
    LoginName: string;          // 登录名
    LoginPwd?: string;         // 密码 (通常不应在前端处理或存储)
    IsDelete?: boolean;        // 是否删除标记
    // 您可以根据API实际返回情况调整这里的类型和可选性
}

//定义用户列表数据 (新增)
const userList = ref<UserData[]>([])

const getUsers = async () => {
    try {
        console.log("尝试调用 GetAccount API 获取用户列表...");
        const response = await GetAccount();
        userList.value = response.data.data;

        console.log('已从API获取并转换用户列表:', userList.value);
    } catch (error) {
        console.error("调用GetAccount API获取用户列表失败:", error);
        ElMessage.error("获取用户列表失败，请检查API接口或网络连接。");
        userList.value = [ // 出错时的备用数据
            { AccountId: 'fallback1', LoginName: '用户加载失败1' },
            { AccountId: 'fallback2', LoginName: '用户加载失败2' },
        ];
    }
};

</script>
